import React, { Component } from 'react';

import styled from 'styled-components'

import BScroll from 'better-scroll';

import qs from 'querystring'

import { Button, Icon, Carousel, WingBlank, Accordion, List, Drawer, NavBar, Modal } from 'antd-mobile';

import { Link } from 'react-router-dom'

import border from '../../../assets/thema/border'

import { DetailContair } from './detailStyle'

import cookie from 'react-cookies'


const alert = Modal.alert;

const Head = border({
    component: styled.div`
        height:.44rem
        width:100%
        line-height:.44rem
        display:flex
        justify-content:space-around
        .left{
            font-size:0.26rem
            a{
                color:#ccc
            }
        }
        .wenzi{
            font-size:0.14rem
        }
        .home{
            font-size:0.24rem
            a{
                color:#ccc
            }
        }
    
    `,
    width: ' 0 0 1px 0 ',
    style: 'solid',
    color: '#ccc',
    radius: 0,
})



class Detail extends Component {
    constructor() {
        super()
        this.state = {
            data: [],
            shopObj: [],
            obj: null,
            datas: ['1', '2', '3'],
            imgHeight: 300,
            dataObj:null,
            imgdata:null
        }
    }



    // 返回上一届
    back = () => {
        const { go } = this.props.history
        go(-1)
    }


    // 加入购物车的点击事件
    addcar = () => {
        console.log('addcar')

        const { search } = this.props.location
        // 从地址栏拿数据
        const serarchObj = qs.parse(search.slice(1))
        // 添加到购物车 - 走本地存储 - 这里本身应该是发送请求给后端，入数据库 
        const shopCar = JSON.parse(localStorage.getItem('shopcar'))
        this.state.obj = {
            ...serarchObj,
            num: 1,
            //这个flag作用是为了后面控制全选按钮的
            flag: true,
            numflag:true
        }
        this.setState({
            obj: {
                ...serarchObj,
                num: 1,
                
            }
        })
        if (shopCar) {
            //条件成立，证明有数据 
            let flag = shopCar.some(item => item.id == serarchObj.id)
            if (flag) {
                //证明这条数据已经存在了
                shopCar.map(item => {
                    if (item.id == serarchObj.id) {
                        item.num++
                        return
                    }
                })
            } else {
                shopCar.push(this.state.obj)
                
                localStorage.setItem('shopcar', JSON.stringify(shopCar))
            }

            // this.state.shopObj.push( this.state.obj )
            alert('你的宝贝已经添加成功')
            localStorage.setItem('shopcar', JSON.stringify(shopCar))



        } else {

            // 没有这条数据 ，直接添加
            alert('你的宝贝已经添加成功')
            this.state.shopObj.push(this.state.obj)
            this.setState({
                shopObj: this.state.shopObj
            })
            localStorage.setItem('shopcar', JSON.stringify(this.state.shopObj))
        }
    }
 
    componentDidMount() {
        fetch('/mock/detailimg.json')//可以请求到数据
        .then(res=>res.json())
        .then(data=>{
            this.setState({
                imgdata:data
            })
            console.log(this.state.imgdata)
        })
        .catch(error=>{
            console.log(error)
        })
        const { search } = this.props.location 
        const serarchObj = qs.parse( search.slice( 1 ))
        setTimeout(() => {
            this.setState({
                datas: [`${serarchObj.goodsimg}`, "http://mp5.jmstatic.com/product/003/714/3714976_std/3714976_1_1000_1000.jpg?v=1564732931&imageView2/2/w/800/q/90", "http://mp5.jmstatic.com/product/003/714/3714976_std/3714976_1_1000_1000.jpg?v=1564732931&imageView2/2/w/800/q/90"],
            });
        }, 100);
    }


    renderImg = () => {
        
        return this.state.datas.map(val => (
            <a
                key={val}
                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
            >
              <img
                src={val}
                alt=""
                style={{ width: '100%', verticalAlign: 'top' }}
                onLoad={() => {
                  // fire window resize event to change height
                  window.dispatchEvent(new Event('resize'));
                  this.setState({ imgHeight: 'auto' });
                }}
              />
            </a> 
        ))
    }

    buy = () => {
        this.props.history.push('/shopcar')
        if (!cookie.load('username', { path: '/' })) {
            alert('未登陆，不能购物哦！')
        }

    }

    render() {
        const { search } = this.props.location
        const serarchObj = qs.parse(search.slice(1))
        return (
            <DetailContair>
                <div className="Contair">
                    <div className="content" >
                            <Head>
                                <p className="left">
                                    <a onClick={this.back}>
                                        <i className = 'fa fa-angle-left' ></i>
                                    </a>
                                </p>
                                
                                <p className="wenzi">{serarchObj.goodstitle}</p>
                                <p className="home">
                                    <Link to="/home/homemain/today">
                                    <i className = 'fa fa-home' ></i>
                                    </Link>
                                    </p>
                            </Head>

                            {/* 轮播图部分 */}
                            <div className="ImgBox" style={{width:'100%'}}>
                                <WingBlank style={{width:'100%'}}>
                                    <Carousel
                                    autoplay={true}
                                    infinite
                                    >
                                    {this.renderImg()}
                                    </Carousel>
                                </WingBlank>
                            </div>
                            
                            <div className="txt">
                                <p>
                                    <span className="zhekoujia ">￥{serarchObj.nowprice}</span>
                                    <del>￥{serarchObj.delprice}</del>
                                </p>
                                <p className="purchase">{serarchObj.jugement}</p>
                            </div>
                            
                            <p className="name">
                                {serarchObj.name}
                            </p>
                        </div>

                        <p className="name">
                            {serarchObj.name}
                        </p>



                        {/* 运费部分 */}
                        <div className="freight" style={{ marginTop: '.1rem', lineHeight: '.3rem' }}>
                            <Link to="/explain"
                                style={{
                                    fontSize: '.14rem',
                                    color: '#000',
                                }}
                            >
                                <span style={{ color: '#ccc', paddingLeft: '0.1rem' }}>运费</span><span className="pinkage"
                                    style={{ paddingLeft: '0.6rem' }} >件数满一，全国包邮</span>
                            </Link>

                        </div>

                        {/* 说明 */}
                        <div className="explain" style={{ marginTop: 10, marginBottom: 10 }}>
                            <Accordion defaultActiveKey="0" className="my-accordion">
                                <Accordion.Panel header="七天拆封无理由退货">
                                </Accordion.Panel>
                                <Accordion.Panel header="非自营（营业执照）" className="pad"></Accordion.Panel>
                                <Accordion.Panel header="七天拆封无理由换货" className="pad">
                                </Accordion.Panel>
                                <Accordion.Panel header="视频红包可低折扣10%" className="pad">
                                </Accordion.Panel>
                                <Accordion.Panel header="支持分期" className="pad">
                                </Accordion.Panel>
                            </Accordion>
                        </div>

                        {/* 底部 */}
                        <div className="footer" style={{
                             position:'fixed',
                             bottom:'0',
                             height:'.48rem',
                             width:'100%',
                             zIndex:'9999',
                             background:'#fff',
                        }}>
                            <Button
                                onClick={this.buy}
                                className="btn" type="warning" style={{
                                    width:'1.28rem',
                                    background: `linear-gradient(210deg, #ffcfdf 0%, #fff1f6 98%)`, position: 'absolute', color: '#000',
                                    right: '1.28rem', fontSize: '0.14rem'
                                }}>立即购买</Button>

                            <Button
                                onClick={this.addcar}
                                className="btn" type="warning" style={{
                                    width:'1.28rem',
                                    background: '#fe4079', position: 'absolute', color: '#000',
                                    right: '0', fontSize: '0.14rem'
                                }}>加入购物车</Button>

                            <div className="shopcar" style={{
                                width:'0.57rem',
                                height:'0.48rem',
                                float:'left',
                                fontSize:'.1rem',
                                background:'#fff',
                                textAlign:'center',
                            }}>
                                <Link
                                style={{
                                    height:'0.48rem',
                                    color:'#979797',
                                    display:'flex',
                                    flexDirection: 'column',
                                    justifyContent:'space-around',
                                }}
                                    to="/shopcar"
                                ><i className='fa fa-shopping-cart'></i>
                                    <span>购物车</span></Link>
                            </div>
                            <div className="shop" style={{
                                textAlign:'center',
                                background:'#fff',
                                width:'0.57rem',
                                height:'0.48rem',
                                float:'left',
                                fontSize:'.1rem',
                            }}>
                                <Link
                                    to="/home/homemain/today"
                                    style={{
                                        height:'0.48rem',
                                        color:'#979797',
                                        display:'flex',
                                        flexDirection: 'column',
                                        justifyContent:'space-around',
                                    }}
                                >
                                    <i className='fa fa-university'></i>
                                    <span>商铺</span></Link>
                            </div>
                        </div>
                    </div>
                
            </DetailContair>
        )
    }
}

export default Detail